package com.proj.hot.widget;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.Window;
import android.widget.TextView;

import com.proj.hot.utils.DownloadFileUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.proj.hot.R;


public class XWDialogLoading extends Dialog implements  DownloadFileUtil.OnDownloadListener{

	String mApkurl,apkFilepath;
	Context mContext;
	int fileSize,downLoadFileSize;
	TextView txt;

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {

			case 1:
				txt.setText("正在下载..."+downLoadFileSize*100/fileSize+"%");
				break;
			case 2:


				final File file = new File(apkFilepath);
				if(file.exists()){
					XWDialogLoading.this.dismiss();
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					intent.setDataAndType(Uri.parse("file:/" + apkFilepath),"application/vnd.android.package-archive");
					mContext.startActivity(intent);
				}


				
				
				break;

			default:
				break;
			}
		}

	};

	@Override
	public void onDownloadFail(String url) {

	}

	@Override
	public void onDownloading(String url, int fileSize, int downedFileLength) {

	}

	@Override
	public void onDownloadSuccess(String url, String path) {
		sendMsg(2);// 通知下载完成
	}




	public XWDialogLoading(Context context, String apkurl) {
		super(context, R.style.transDialog);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.mApkurl = apkurl;
		this.mContext = context;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.update_view_dialogloading);
		// 设置标题
		setCanceledOnTouchOutside(false);
		setCancelable(false);
		txt=(TextView) findViewById(R.id.txt);
		load();
	}


	
	void load() {


		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub

						try {
							downLoadFile(mApkurl);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

			}
		}).start();

	}



	private void sendMsg(int flag) {
		Message msg = new Message();
		msg.what = flag;
		mHandler.sendMessage(msg);
	}






	//下载apk程序代码
	protected File downLoadFile(String httpUrl) throws MalformedURLException {
		// TODO Auto-generated method stub final String fileName = "updata.apk";

	// 下载函数
	String filename = httpUrl.substring(httpUrl.lastIndexOf("/") + 1);


//        String dic= mContext.getFilesDir().getAbsolutePath();

		String dic=mContext.getExternalCacheDir().getAbsolutePath();

		File tmpFile = new File(dic);
		if (!tmpFile.exists()) {
			tmpFile.mkdir();
		}
		final File file = new File(dic +"/"+ filename);
		if(file.exists()){
			file.delete();
		}


		apkFilepath=dic +"/"+ filename;
		try {
			URL url = new URL(httpUrl);
			try {
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				InputStream is = conn.getInputStream();
				this.fileSize = conn.getContentLength();// 根据响应获取文件大小
				FileOutputStream fos = new FileOutputStream(file);
				byte[] buffer = new byte[256];
				conn.connect();
				downLoadFileSize = 0;
				int len=-1;
				while ((len=is.read(buffer)) != -1) {
					fos.write(buffer,0,len);  //在这里使用另一个重载，防止流写入的问题.
					downLoadFileSize += len;;
					sendMsg(1);// 更新进度条
				}



				conn.disconnect();
				fos.close();
				is.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				XWDialogLoading.this.dismiss();

				//  53002
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mHandler.sendEmptyMessageDelayed(2,1000);
		return file;
	}



	

}
